import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    value: '',
    searchGoodsList: [],
    // 历史搜索记录
    kwList: []
  }

  onLoad(){
    this.kwList = wepy.getStorageSync('kwList') || []
  }

  computed = {
    isShowHhistory(){
      if(this.value.length<=0){
        return true
      }
      return false
    }
  }

  methods = {
    onSearch(e) {
      // console.log(e.detail)
      const kw = e.detail.trim()

      if (kw.length <= 0) {
        return
      }
      if(this.kwList.indexOf(kw) === -1){
        this.kwList.unshift(kw)
      }
      this.kwList = this.kwList.slice(0, 10)
      wepy.setStorageSync('kwList', this.kwList)

      wepy.navigateTo({
        url: '/pages/goods_list?query=' + kw
      })
    },

    onCancel() {
      this.searchGoodsList = []
    },

    onChange(e) {
      this.value = e.detail

      if (e.detail.trim().length <= 0) {
        this.searchGoodsList = []
        return
      }

      this.getSearchGoodsList(e.detail)
    },

    goGoodsDetail(goods_id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + goods_id
      })
    },

    goGoosList(query){
      wepy.navigateTo({
        url: '/pages/goods_list?query=' + query
      })
    },

    deleteHistoryList(){
      this.kwList = []
      wepy.setStorageSync('kwList', [])
    }
  }

  async getSearchGoodsList(searchStr) {
    const { data: res } = await wepy.get('/goods/qsearch', { query: searchStr })

    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.searchGoodsList = res.message
    this.$apply()
  }
}
